/**
 * Created by Administrator on 2016/10/5.
 */
var user = (function($){
    return{

        tableObj : null,
        otherElem : {},
        // 初始化
        init: function(){
            type = momo.getURLElement('type'); // 全局变量
            momo.initPage();// 左边菜单栏
            this.addBtnEvent();// 给“搜索”“重置”按钮添加点击事件

            //动态接受参数进行设置
            var isIFrame = momo.getURLElement("isIFrame");// 是否是模态框
            //console.log( isIFrame );

            if( isIFrame ) { // 是模态框

                // iframe内部页面 移除 头部、左边菜单栏
                $('#header').remove();
                $('#sidebar').remove();
                $('.breadcrumbs').remove();
                $('.page-header').remove();
                $('.page-content').css('border', 'none');

                // 根据搜索条件初始化表格数据
                var name = $('#searchName').val();
                var phone = $('#searchPhone').val();
                var account = $('#searchAccount').val();

                var _data = {
                    "name": name,
                    "phone": phone,
                    "account": account,
                };
                this.initTable( _data, true );// 初始化表格

            }else{
                this.initTable( {}, false );// 初始化表格
            }

            // 导出
            this.otherElem = { };
        },

        // 初始化表格
        initTable: function( data, isIFrame ){
            console.log(data);
            var _self = this;

            var url = 'PUser/index';
            var editUrl = '';
            var colName = ['序号','姓名','手机号码','银行卡号','积分','抽奖次数','寄送地址','注册时间'];//,'操作'];
            var colModal = [
                { index: 'id', width:5, textOverflowEllipsis: true, sort: false, formatter: setNum},
                { index: 'name', width:10, textOverflowEllipsis: true, sort: false },
                { index: 'phone', width:15, textOverflowEllipsis: true, sort: false },
                { index: 'account', width:20, textOverflowEllipsis: true, sort: false },
                { index: 'score', width:10, textOverflowEllipsis: true, sort: false },
                { index: 'lottery_time', width:10, textOverflowEllipsis: true, sort: false },
                { index: 'address', width:20, textOverflowEllipsis: true, sort: false },
                { index: 'add_time', width:10, textOverflowEllipsis: true, sort: false },
              //  { index: 'id', width:40, textOverflowEllipsis: true, sort: false, formatter: setOperate.bind(_self) },// 传入id，操作表单
            ];

            // 如果是iframe，不显示“操作”
            if( isIFrame ){
                colName.pop();
                colModal.pop();
            }

            var _data = {};
            if( data != undefined ) _data = $.extend( _data, data );
            this.tableObj = new $.jqGrid( $('#jqGrid'), url, _data, colName, colModal, undefined, false, true, editUrl );
             console.log(this.tableObj);


            // （辅助函数）设置序号
            function setNum( val, rowData, index ) {
                var _num = ( _self.tableObj.currentPage - 1 ) *  _self.tableObj.data.page_size + ( index + 1 );
                return '<span>' + parseInt( _num ) + '</span>';
            }  
            // （辅助函数）设置操作（this是 lottery对象）
            function setOperate( val, rowData ){

                var _str =  '<a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="user.edit(\'' + val + '\');">编辑</a>';
                //if( momo.getURLElement("isIFrame") ) return '';// 是模态框，不允许操作
                return _str;
            }
        },

        edit: function(id){
            window.location.href = 'edit.html?id='+id;
        },

        import:function(id){
            var message = $("#importModal").text();
            bootbox.dialog({
                    title: "导入用户信息",
                    message: message,
                    onEscape: function () {
                    }
                });
            $("#import_rush_id").val(id);
        },

        view:function(id){
            window.location.href = 'view.html?id='+id;
        },
     
        // 给“搜索”“重置”按钮、“展开/收起日志”、“取消订单”按钮、订单备注编辑、保存、取消按钮 添加点击事件
        addBtnEvent: function(){

            var _self = this;

            // 点击搜索按钮
            $('.searchBtn').click( function(){

                var name = $('#searchName').val();
                var phone = $('#searchPhone').val();
                var account = $('#searchAccount').val();

                var _data = {
                    "name": name,
                    "phone": phone,
                    "account": account,
                };
                this.tableObj.reloadData( _data, true );

                this.otherElem = $.extend( this.otherElem, _data);// 导出功能

            }.bind( this ));

            // 点击重置按钮
            $('.resetBtn ').click( function(){
                $("#searchName").val('');
                $("#searchPhone").val('');
                $("#searchAccount").val('');

            });
            $("#import").click(function(){
                var message = $("#importModal").text();
                bootbox.dialog({
                    //size: 'large',
                    title: "导入积分",
                    message: message,
                    onEscape: function () {
                    }
                });
            })

            $('.downBtn').click(function(){
                var name = $("#searchName").val();
                var phone = $("#searchPhone").val();
                var account = $("#searchAccount").val();
                var params="name="+encodeURI(name)+"&phone="+encodeURI(phone)+"&account="+encodeURI(account);
                location.href=momo.baseURL+"PUser/export?"+params;
            })

            $(document).on('click', '.import', function(){
                var formData = new FormData();
                formData.append("file",$("#import_file")[0].files[0]);
                $.ajax({ 
                    url : momo.baseURL + 'PUser/import', 
                    type : 'POST', 
                    data : formData, 
                    // 告诉jQuery不要去处理发送的数据
                    processData : false, 
                    // 告诉jQuery不要去设置Content-Type请求头
                    contentType : false,
                    beforeSend:function(){
                        console.log("正在进行，请稍候");
                    },
                    success : function(data) { 
                        if(data.errcode==0){
                            alert(data.errmsg);
                            bootbox.hideAll();
                            _self.tableObj.reloadData();
                        }else{
                            alert( data.errmsg );
                        }
                    }, 
                    error : function(responseStr) { 
                        console.log(responseStr);
                    } 
                });
                return false;
            });
           

       

        },
    }
})(jQuery);

var init = user.init.bind( user );
